from pysnmp.hlapi.asyncio import *
import asyncio

from .read_csv import get_raw_data,get_oid_data
raw_data = get_raw_data()
oid_data = get_oid_data()

# 设置新的事件循环策略（避免 Proactor 问题）
policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(policy)

async def _snmpget(ip:str = None ,oid:str = None):
    
    # 定义 SNMP 连接参数和 OID
    community_data = CommunityData('public')  # SNMP 社区字符串
    transport_target = await UdpTransportTarget.create((ip, 161))  # SNMP Agent 地址和端口
    object_identity = ObjectIdentity(oid)  # 示例 OID：sysDescr

    # 发送 GET 请求
    error_indication, error_status, error_index, var_binds = await get_cmd(
        SnmpEngine(),
        community_data,
        transport_target,
        ContextData(),
        ObjectType(object_identity)
    )
    result = {}
    # 处理响应结果
    if error_indication:
        return {"error": str(error_indication)+f"oid:{oid},ip:{ip}"}
    elif error_status:
        return {"error": f"{error_status.prettyPrint()} at {error_index}"+f"oid:{oid},ip:{ip}"}
    else:
        for name, value in var_binds:
            result[str(name)] = str(value)
        return result

def snmpget(ip:str = None ,wr_type:str = None,mib_name:str = None):
    if ip == None or wr_type == None or mib_name == None: return {"error": "请输入正确的参数"}
    oid = raw_data[wr_type][mib_name]
    result = asyncio.run(_snmpget(ip,oid))
    for key,value in result.items():
        if key == "error":
            result = {"error": value}
            print(result)
        else:
            result = {oid_data[wr_type][oid]:value}
    return result
   

if __name__ == "__main__":
    # 运行异步函数
    result = asyncio.run(_snmpget("10.10.14.30",".1.3.6.1.4.1.96.103.1.1.1.2"))
    print(result)